<template>
    <div class="appointment-add" :class="page_i == 3 ? 'acitve' : ''">
        <div class="header-box flex_between">
            <div class="header-left">
                <div class="back" v-if="is_back && !is_customer">
                    <i class="el-icon-arrow-left" @click="backFun"></i>
                </div>
                <div class="title">
                    {{ !is_edit ? "新建预约单" : "修改预约单" }}
                </div>
            </div>
            <div class="header-right">
                <el-button size="mini" type="primary" plain @click="backBtn" v-if="openNewAppointment">返回</el-button>
            </div>
        </div>
        <div class="appointment-box">
            <div class="pop-customer-select" v-if="!is_edit && !is_customer && !openNewAppointment">
                <!-- 选择客户 -->
                <customerSelect ref="customerSelect" :top_num_search="55" :top_num_screen="156" :list_box_h="160"
                    @getCustomerData="getCustomerData"></customerSelect>
            </div>
            <div class="appointment-info-box" :class="is_edit || is_customer ? 'w-all' : ''"
                :style="{ width: openNewAppointment ? '100%' : 'calc(100% - 345px)' }">
                <div class="appointment-info comm-list">

                    <!-- 选择服务的对象（客户） -->
                    <div class="choice-box">
                        <div class="choice-info">
                            <div class="choice-info-left">
                                <div class="img-box">
                                    <img :src="customerInfo.avatar
                                        ? customerInfo.avatar
                                        : require('../../static/images/Uimg.png')
                                        " />
                                </div>
                                <div class="choice-content">
                                    <div class="title">
                                        <span>
                                            {{
                                                customerInfo.name
                                                    ? customerInfo.name
                                                    : "请选择1个客户"
                                            }}</span>
                                        <span>{{
                                            customerInfo.company
                                                ? customerInfo.company
                                                : ""
                                        }}</span>
                                    </div>
                                    <div class="phone" v-if="customerInfo.cellphone">
                                        <span>{{
                                            customerInfo.cellphone
                                        }}</span>
                                    </div>
                                </div>
                            </div>

                            <div class="choice-info-right" v-if="!is_edit && !is_customer && false">
                                <el-button size="mini" :type="customerInfo.name ? '' : 'primary'"
                                    @click="selectCustom">{{
                                        customerInfo.name ? "更换" : "选择客户"
                                    }}</el-button>
                                <el-button size="mini" type="danger" v-if="customerInfo.name"
                                    @click="delCustomer">移除</el-button>
                            </div>
                        </div>
                    </div>

                    <!-- 选择的服务类型 -->
                    <!-- 卡项服务 -->
                    <template v-if="serType == 'cardServe'">
                        <div class="select-content" v-if="customerInfo.name">
                            <div class="content-box" v-show="projectData.length > 0">
                                <div class="content-row" v-for="item in projectData" :key="item.proid">
                                    <div class="content-info-box">
                                        <div class="content-info">
                                            <div class="content-title">
                                                <span>{{ item.title }}</span>
                                            </div>
                                            <div class="content-dot">
                                                <span> 剩余{{ item.serv_left }} 次</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="content-but">
                                        <div class="content-num">
                                            <span>服务次数</span>
                                            <el-input-number size="mini" v-model="item.serv_qty" :min="0"
                                                :max="item.serv_left"></el-input-number>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>

                    <!-- 项目服务 -->
                    <template v-else>
                        <div class="select-content" v-show="customerInfo.name">
                            <div class="select-content-title">
                                <div class="title"><span>选择服务</span></div>
                                <div class="but" v-if="!is_customer">
                                    <el-button size="mini" type="primary" @click="selectProject('1')">{{
                                        projectData.length > 0
                                            ? "添加服务"
                                            : "可选择此客户1个或多个服务"
                                    }}</el-button>
                                </div>
                            </div>
                            <div class="content-box" v-show="projectData.length > 0">
                                <div class="content-row" v-for="item in projectData" :key="item.proid">
                                    <div class="content-info-box">
                                        <div class="content-info">
                                            <div class="content-title">
                                                <span>{{ item.title }}</span>
                                            </div>
                                            <div class="content-dot">
                                                <span>{{ item.shop_name }}</span><span>剩余{{
                                                    item.serv_left
                                                    }}次</span><span>总价{{ item.serv_total }}</span><span>有效期：{{
                                                        item.endtime_txt
                                                    }}</span>
                                                <el-button size="mini" v-if="isGetLimitYyEffctiveDate" type="primary"
                                                    @click="clickIsMaskShowFun(item)">更改有效期</el-button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="content-but">
                                        <div class="content-num">
                                            <span>服务次数</span>
                                            <el-input-number size="mini" v-model="item.serv_qty" :min="1"
                                                :max="item.serv_left"></el-input-number>
                                        </div>
                                        <div class="but-box-pro" v-if="!is_customer">
                                            <el-button size="mini" @click="selectProject('2', item)">更改</el-button>
                                            <el-button size="mini" type="danger"
                                                @click="delProject(item)">移除</el-button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>

                    <!-- 服务人和时间信息 -->
                    <appointmentTiem :page_i="page_i" :page_show_i="page_show_i" :is_edit="is_edit"
                        ref="appointmentTiem"></appointmentTiem>
                </div>
                <div class="but-box">
                    <div class="but avt" @click="submitAppointment">
                        <span>提交预约单</span>
                    </div>
                </div>
            </div>
        </div>
        <!-- 选择客户 -->
        <!-- <popCustomerSelect
            :page_i="page_i"
            ref="popCustomerSelect"
            @getCustomerData="getCustomerData"
        ></popCustomerSelect> -->
        <!-- 选择服务 -->
        <popProjectSelect ref="popProjectSelect" @getProjectData="getProjectData"></popProjectSelect>

        <el-dialog title="更改有效日期" :visible.sync="maskDialogIsShow" width="500px" :before-close="handleClose">
            <div>
                <div>
                    <el-radio v-model="maskRadioVal" :label="1">永不过期</el-radio>
                </div>
                <div>
                    <el-radio v-model="maskRadioVal" :label="2">具体日期</el-radio>
                    <el-date-picker @change="maskPickerFun" size="mini" :disabled="maskRadioVal == 2 ? false : true"
                        v-model="maskPickerVal" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
                    </el-date-picker>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="maskDialogIsShow = false">取 消</el-button>
                <el-button type="primary" @click="edifSaveFun">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import appointmentTiem from "./appointmentTiem.vue";
import popCustomerSelect from "./popCustomerSelect.vue";
import customerSelect from "./customerSelect.vue";
import popProjectSelect from "./popProjectSelect.vue";
import config from "@/js/conf/Config.js";
import accessCtrl from "@/js/limit/AccessCtrl.js";
import { mapGetters } from 'vuex';
export default {
    name: "appointment-add",
    components: {
        appointmentTiem,
        popCustomerSelect,
        popProjectSelect,
        customerSelect,
    },
    props: ["page_i", "page_show_i", "is_back", "options"],

    data() {
        return {
            serType: null, // 决定是  项目服务：默认null， 还是 卡项服务：cardServe
            customerInfo: {}, //已选客户数据
            projectData: [], //已选服务数据
            customerid: "", //请求服务的id
            replacePid: "", //更换的服务id
            is_edit: false, //是否编辑
            bookid: "", //编辑的id
            is_customer: false, //是否客户过来的预约

            maskDialogIsShow: false, // 是否显示修改有效日期弹出 
            maskRadioVal: 1,
            maskPickerVal: "",
            endtime_str: "",
            proid: "",
            isMaskShow: false,

            isGetLimitYyEffctiveDate: "",
            openNewAppointment: false,
        };
    },

    // 监听options
    watch: {
        options: {
            handler(newVal) {
                if (newVal) {
                    this.serType = newVal.serType;
                }
            },
            deep: true,
            immediate: true,
        }
    },

    async created() {
        this.isGetLimitYyEffctiveDate = await accessCtrl.getLimitYyEffctiveDate();
    },

    computed: {
        ...mapGetters({
            appointmentData: 'common/appointmentData'
        })
    },

    methods: {
        async initData(data) {
            if (!data) {
                this.emptyData();
            } else {
                this.customerInfo = {};
                this.projectData = [];
                this.customerid = "";
                this.replacePid = "";
                this.is_edit = false;
                this.is_customer = false;
                this.$refs.appointmentTiem.is_destroy_editing = "1";
                this.$refs.appointmentTiem.getServiceData(data);
            }
            this.$nextTick(() => {
                this.$refs.customerSelect.initData();
            });
            console.log("this.appointmentData=", this.appointmentData)
            if (this.appointmentData && this.appointmentData?.customerInfo) {
                this.customerInfo = this.appointmentData.customerInfo;
                this.projectData = this.appointmentData.projectData;
                this.customerid = this.appointmentData.customerInfo.id;
                this.openNewAppointment = true;
            } else {
                this.openNewAppointment = false;
            }
        },
        // 客户页面过来的预约操作
        customerAppointment(data) {
            this.emptyData();
            this.is_customer = true;
            this.customerInfo = data.customerInfo;
            this.customerid =
                data.customerInfo.id || data.customerInfo.customerid;
            this.projectData = data.projectData;
        },
        // 订单过来的预约操作
        async orderModificationFun(data) {
            this.customerInfo = data.customer_info;
            this.customerid = data.customerid;
            let url = config.YY_YUYUE_BOOK_MYORI_LS;
            let param = {
                customerid: data.customerid,
                odid: data.id,
            };
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                if (res.data.ls) {
                    res.data.ls.map((v) => {
                        v.serv_left = Number(v.serv_left);
                    });
                }
                this.projectData = res.data.ls || [];
            }
        },
        // 编辑预约单
        modificationFun(data) {
            this.emptyData();
            this.is_edit = true;
            this.$refs.appointmentTiem.is_destroy_editing = "2";
            this.geteditInfo(data);
        },
        // 获取编辑信息
        async geteditInfo(data) {
            let param = {
                bookid: data.bookid,
            };
            this.bookid = data.bookid;
            let url = config.YY_YUYUE_BOOK_EDIT_INFO;
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                res.data.pro_list.map((v) => {
                    v.serv_left = Number(v.serv_left);
                });
                res.data.staff_info.id = res.data.staff_info.staffid;
                this.customerid = res.data.customer_info.customerid;
                this.customerInfo = res.data.customer_info;
                this.projectData = res.data.pro_list;

                const obj = {
                    book_info: res.data.book_info,
                    staff_info: res.data.staff_info,
                    hour_allow: res.data.hour_allow,
                };
                this.$refs.appointmentTiem.getEditServiceData(obj);
            }
        },
        // 清空
        emptyData() {
            this.customerInfo = {};
            this.projectData = [];
            this.customerid = "";
            this.replacePid = "";
            this.is_edit = false;
            this.is_customer = false;
            this.bookid = "";
            this.$refs.appointmentTiem.is_destroy_editing = "1";
            this.$refs.appointmentTiem.emptyData();
        },
        // 提交预约单
        async submitAppointment() {
            let param = {
                customerid: this.customerid,
                staffid: this.$refs.appointmentTiem.staffid,
                h_from: this.getHour("h_from") || "",
                h_to: this.getHour("h_to") || "",
                proid_ls: this.getPorject(),
                timestr: this.getTimestr(),
            };
            if (this.is_edit) {
                param.bookid = this.bookid;
            } else {
                param.tlong = this.$refs.appointmentTiem.tlong;
            }
            if (!param.customerid) {
                this.$msg({ title: "请选择客户" });
                return;
            }
            if (param.proid_ls.length == 0) {
                this.$msg({ title: "请选择服务" });
                return;
            }
            if (!param.staffid) {
                this.$msg({ title: "请选择服务人" });
                return;
            }
            if (!param.h_from) {
                this.$msg({ title: "请选择时间" });
                return;
            }
            let url = this.is_edit
                ? config.YY_YUYUE_BOOK_EDIT_SAVE
                : config.YY_YUYUE_BOOK_ADD;
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                this.$msg({ title: "提交成功" });
                setTimeout(() => {
                    if (this.is_customer) {
                        this.$emit("upDataList");
                    }
                    if (this.is_edit) {
                        this.backFun();
                    }
                    if (this.page_i == 3) {
                        this.emptyData();
                    }
                    if (this.openNewAppointment) {
                        this.backBtn()
                    }
                }, 1000);
            }
        },
        getPorject() {
            let data = this.projectData;
            let proid_ls = [];
            if (data.length > 0) {
                data.map((v) => {
                    proid_ls.push({
                        proid: v.proid,
                        serv_qty: v.serv_qty,
                    });
                });
            }
            return proid_ls;
        },
        getTimestr() {
            let data = this.$refs.appointmentTiem.timestrList;
            let timestr = "";
            data.map((v) => {
                if (v.is_acitve) {
                    timestr = v.timestr;
                }
            });
            return timestr;
        },
        getHour(type) {
            let data = this.$refs.appointmentTiem.hourList;
            let hour = [];
            data.map((v) => {
                if (v.is_acitve) {
                    hour.push(v.hour);
                }
            });
            if (type == "h_from") {
                return hour[0];
            } else {
                return hour[hour.length - 1];
            }
        },
        // 删除客户
        delCustomer() {
            this.customerInfo = {};
        },
        // 删除服务
        delProject(item) {
            this.projectData.map((v, i) => {
                if (v.proid == item.proid) {
                    this.projectData.splice(i, 1);
                }
            });
        },
        // 选中的客户
        getCustomerData(data) {
            this.projectData = [];
            this.customerInfo = data;
            this.customerid = data.id;
        },
        // 选中/更换的服务
        getProjectData(data, type) {
            if (type == 1) {
                data.map((v) => {
                    v.serv_qty = 1;
                    v.serv_left = Number(v.serv_left);
                });
                if (this.is_edit) {
                    let arrObj = this.projectData.concat(data);
                    let map = new Map();
                    for (let item of arrObj) {
                        if (!map.has(item.proid)) {
                            map.set(item.proid, item);
                        }
                    }
                    this.projectData = [...map.values()];
                } else {
                    this.projectData = data;
                }
            } else {
                this.projectData.map((v, i) => {
                    if (v.proid == this.replacePid) {
                        data.serv_qty = 1;
                        data.serv_left = Number(data.serv_left);
                        this.projectData.splice(i, 1, data);
                    }
                });
            }
        },

        // 打开客户列表
        selectCustom() {
            this.$refs.popCustomerSelect.initData();
        },

        // 打开服务列表
        selectProject(type, item = null) {
            if (item) {
                this.replacePid = item.proid;
            }
            const data = {
                customerid: this.customerid,
                selectType: type,
                existenceListData: this.projectData,
            };
            this.$refs.popProjectSelect.initData(data);
        },

        // 返回
        backFun() {
            this.$emit("backFun", this.is_edit, this.bookid);
        },

        // 如果从客户页面过来的预约，则返回
        backBtn() {
            this.openNewAppointment = false;
            this.$store.commit('common/clearAppointmentData');
            this.$router.go(-1);
        },

        // 点击更改有效日期按钮
        clickIsMaskShowFun(row) {
            this.proid = row.proid;
            this.maskDialogIsShow = true;
        },
        // 更改有效日期接口请求
        async edifSaveFun() {
            let url = config.YY_YUYUE_MYPRO_EDIT_SAVE;
            let endtime_str = this.maskRadioVal == 1 ? 'ever' : this.endtime_str;
            let param = {
                endtime_str: endtime_str,
                proid: this.proid,
            };
            if (this.maskRadioVal == 2 && endtime_str == "") return this.$message.error('请选择日期！');
            let res = await this.$api({ url: url, data: param });
            if (res.status == 1) {
                this.$message({
                    message: res.msg,
                    type: 'success'
                });
                this.maskDialogIsShow = false;
                this.isMaskShow = false;
                this.$emit("upDataList");
            }
        },
        handleClose() {
            this.filterBoxDialog = false;
            if (this.isReamType == false) {
                this.resetFun();
            }
        },
        maskPickerFun(val) {
            this.endtime_str = val;
        },
    },
    // 添加 deactivated 钩子（如果使用了 keep-alive）
    deactivated() {
        this.$store.commit('common/clearAppointmentData');
    }
};
</script>

<style lang="scss" scoped>
.appointment-add {
    height: 100vh;
    width: 100%; //calc(100% - 417px);
    background-color: #fff;

    &.acitve {
        // margin-left: 72px;
        // width: calc(100% - 72px);
    }

    .header-box {
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px #e8dcdc solid;
        padding: 0 10px;
        padding-right: 20px;
        display: flex;

        .header-left {
            display: flex;

            .back {
                font-size: 20px;
                margin-right: 10px;
                cursor: pointer;
            }

            .title {
                font-size: 18px;
            }
        }
    }

    .appointment-box {
        height: 100%;
        display: flex;

        .pop-customer-select {
            width: 345px;
            height: 100%;
            padding-top: 65px;
            border-right: 1px #ececec solid;
        }

        .appointment-info-box {
            position: relative;
            width: calc(100% - 345px);
            height: calc(100% - 50px);

            &.w-all {
                width: 100%;
            }

            .but-box {
                position: absolute;
                left: 0;
                bottom: 0;
                height: 60px;
                width: 100%;
                border-top: 1px #e8dcdc solid;
                background: #fff;
                display: flex;
                align-items: center;
                justify-content: flex-end;

                .but {
                    height: 100%;
                    padding: 0 20px;
                    font-size: 16px;
                    display: flex;
                    align-items: center;
                    cursor: pointer;

                    &.avt {
                        background: #3388ff;
                        color: #fff;

                        &:hover {
                            background: #5498f7;
                        }
                    }
                }
            }

            .appointment-info {
                height: calc(100% - 80px);
                overflow: auto;
                padding: 10px;

                .choice-box {
                    border: 1px #e8dcdc solid;
                    margin-bottom: 20px;
                    padding: 10px;

                    .choice-info {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .choice-info-left {
                            display: flex;
                            align-items: center;

                            .img-box {
                                width: 80px;
                                height: 80px;
                                border-radius: 50%;
                                overflow: hidden;
                                margin-right: 10px;

                                img {
                                    width: 100%;
                                    height: 100%;
                                    object-fit: cover;
                                }
                            }

                            .choice-content {
                                font-size: 14px;

                                .title {
                                    span {
                                        margin-right: 10px;
                                    }
                                }
                            }
                        }

                        .choice-info-right {
                            display: flex;
                            align-items: center;
                        }
                    }
                }

                .select-content {
                    border: 1px #e8dcdc solid;
                    margin-bottom: 20px;

                    .select-content-title {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 10px;
                        height: 30px;

                        .title {
                            font-size: 14px;
                            font-weight: bold;
                        }
                    }

                    .content-box {
                        border-top: 1px #e8dcdc solid;
                        padding: 10px 0;
                        font-size: 14px;

                        .content-row {
                            padding: 0 10px;
                            border-bottom: 1px #e8dcdc solid;
                            margin-bottom: 10px;
                            padding-bottom: 10px;

                            &:last-child {
                                margin-bottom: 0;
                                padding-bottom: 0;
                                border: none;
                            }

                            .content-info-box {
                                display: flex;
                                align-items: center;
                                justify-content: space-between;

                                .info {
                                    display: flex;
                                    align-items: center;
                                }

                                .img-box {
                                    width: 80px;
                                    height: 80px;
                                    margin-right: 10px;
                                    border-radius: 5px;
                                    overflow: hidden;

                                    img {
                                        width: 100%;
                                        height: 100%;
                                        object-fit: cover;
                                    }
                                }

                                .content-info {
                                    .content-title {
                                        span {
                                            margin-right: 10px;
                                        }

                                        .tag {
                                            font-size: 12px;
                                            padding: 0 3px 2px;
                                            border: 1px #ff7b23 solid;
                                            color: #ff7b23;
                                            border-radius: 3px;
                                        }
                                    }

                                    .content-dot {
                                        span {
                                            font-size: 12px;
                                            color: #949494;
                                            margin-right: 20px;
                                        }
                                    }
                                }
                            }

                            .content-but {
                                display: flex;
                                justify-content: space-between;
                                margin-top: 10px;

                                .content-num {
                                    span {
                                        margin-right: 10px;
                                        font-weight: bold;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>